export const selectTypeList = ["select", "autoComplete"];
export const inputTypeList = ["input", "number", "textarea"];

export function handleTailValue(tail, value, ctx) {
  if (!ctx) return;
  const tailArr = tail.split(".");
  let temp = ctx;
  for (let i = 0; i < tailArr.length - 1; i++) {
    temp = temp[tailArr[i]];
  }
  temp[tailArr[tailArr.length - 1]] = value;
}

export function buildForm(VO) {
  // console.log("debug log --> ", VO);
  const fieldKeys = Object.keys(VO);
  const form = {};
  const formConfig = {};
  const rules = {};
  const selectMap = {};
  for (let i = 0; i < fieldKeys.length; i++) {
    const key = fieldKeys[i];
    form[key] = VO[key]["decorator"]["initialValue"] || null;
    formConfig[key] = {
      label: VO[key]["wrapper"]["label"],
      prop: key,
      sort: VO[key]["sort"],
      type: VO[key]["type"],
      customize: VO[key]["customize"],
      extend: VO[key]["extend"]
    };
    if (selectTypeList.includes(VO[key]["type"]) || VO[key]["type"] === "area" || VO[key]["type"] === "date") {
      formConfig[key]["visible"] = false;
      selectMap[key] = VO[key]["decorator"]["initialValue"] || null;
    }
    const sourceRules = VO[key]["decorator"]["rules"];
    // console.log("debug log --> ", sourceRules);
    if (sourceRules && sourceRules.length > 0) {
      const { tempRules, isRequired } = transformRules(VO[key]["decorator"]["rules"], VO[key]["type"]);
      rules[key] = tempRules;
      formConfig[key]["isRequired"] = isRequired;
    }
    // console.log("debug log --> ", formConfig);
  }
  return { form, formConfig, rules, selectMap };
}

function transformRules(rules, type) {
  const tempRules = [];
  let isRequired = false;
  const typeCur = type === "number" ? "number" : "string";
  for (let i = 0; i < rules.length; i++) {
    const rule = rules[i];
    if (rule.required || rule.required === false) {
      isRequired = rule.required;
      tempRules.push({
        ...rule,
        type: typeCur,
        trigger: ["change", "blur"]
      });
    } else if (rule.pattern) {
      tempRules.push({
        ...rule,
        regexp: new RegExp(rule.pattern),
        type: typeCur,
        trigger: ["change", "blur"]
      });
    } else {
      tempRules.push({
        ...rule,
        type: typeCur,
        trigger: ["change", "blur"]
      })
    }
  }
  return { tempRules, isRequired };
}